import { Request, Response } from "express";
import { Token } from "../token";

export interface IAuthorization {
  userId: string;
}

export const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export function checkAuthorization(req: Request, res: Response) {
  const Authorization = req.get("Authorization") as string;
  if (!Token.checkToken(Authorization)) {
    res.status(401).send({
      data: {
        isLogin: false,
      },
      errorCode: "401",
      errorMessage: "请先登录！",
      success: true,
    });
    return true;
  }
  return false;
}

export function getUserId(req: Request, res: Response) {
  const Authorization = req.get("Authorization") as string;
  const resDecode = Token.decodeToken<IAuthorization>(Authorization);
  if (!resDecode) {
    res.send({
      success: false,
      data: null,
      errorCode: "700",
      errorMessage: "令牌过期",
    });
    return false;
  }
  return resDecode.payload.data.userId;
}
